from flask_login import UserMixin
from werkzeug.security import check_password_hash, generate_password_hash
from main import db
from config import PASSWORD_SALT
import datetime


class TagUser(db.Model, UserMixin):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_name = db.Column(db.String(20), nullable=False)
    password = db.Column(db.String(20), nullable=False)
    nick_name = db.Column(db.String(20), nullable=True, default="书迁用户")
    search_engine_id = db.Column(db.Integer, nullable=False, default=0)
    wallpaper = db.Column(db.String(512), nullable=True)

    user_default_category_id = db.Column(db.Integer, db.ForeignKey("category.id"), nullable=True)
    user_default_category = db.relationship('TagCategory', foreign_keys=[user_default_category_id], lazy=True)

    create_at = db.Column(db.DateTime, default=datetime.datetime.now)

    def generate_password_hash(self, password):
        self.password = generate_password_hash(password + PASSWORD_SALT)

    def check_password_hash(self, password):
        return check_password_hash(self.password, password + PASSWORD_SALT)

    def to_map(self):
        return {
            "username": self.user_name,
            "nickname": self.nick_name
        }
